package com.myblog.controller;

import com.myblog.common.ResultInfoFactory;
import com.myblog.model.po.SysPermission;
import com.myblog.service.SysPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/permission")
@Slf4j
public class SysPermissionController {

    private static final String HTML_PREFIX="system/permission/";

    @Autowired
    private SysPermissionService sysPermissionService;

    @GetMapping(value = {"/",""})
    @PreAuthorize("hasAuthority('sys:permission')")
    public String permisson(){
        return  HTML_PREFIX+"permission-list";
    }

    @GetMapping(value = {"/form","/form/{id}"})
    @PreAuthorize("hasAnyAuthority('sys:permission:add','sys:permission:edit')")
    public String form(@PathVariable(required = false) Long id, Model model){
        log.info("id="+id);
        if(id !=null){
            SysPermission permission = sysPermissionService.getById(id);
            SysPermission permissionParent = sysPermissionService.getById(permission.getParentId());
            if(permissionParent!=null){
                permission.setParentName(permissionParent.getName());
            }
            model.addAttribute("permission",permission);
        }else {
            model.addAttribute("permission",new SysPermission());
        }

        return  HTML_PREFIX+"permission-form";
    }


    @PreAuthorize("hasAuthority('sys:permission:list')")
    @PostMapping("/list")
    @ResponseBody
    public ResultInfoFactory list(){
        List<SysPermission> list = sysPermissionService.list();
        return ResultInfoFactory.success(list);
    }


    @PreAuthorize("hasAnyAuthority('sys:permission:add','sys:permission:edit')")
    @RequestMapping(value = "",method = {RequestMethod.POST,RequestMethod.PUT})
    public String saveOrUpdate(SysPermission sysPermission){
        sysPermissionService.saveOrUpdate(sysPermission);
        return "redirect:/permission";
    }

    @PreAuthorize("hasAuthority('sys:permission:delete')")
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResultInfoFactory deleteById(@PathVariable Long id){
        sysPermissionService.deleteById(id);
        return ResultInfoFactory.success();
    }



}
